<!-- Message.vue -->
<template>
  <div
    class="message"
    :class="{
      sent: message.sender === userInfo.userId,
      received: message.receiver === userInfo.userId,
    }"
  >
    <img
      src="@/static/image/tx-1.png"
      alt="Avatar"
      class="avatar"
      v-if="message.sender === userInfo.userId"
    />
    <img
      :src="avatarUrl || require('@/static/image/head.png')"
      alt="Avatar"
      class="avatar"
      v-if="message.receiver === userInfo.userId"
    />
    <div class="content" v-if="message.type === 'text'">
      <p class="text">{{ message.content }}</p>
    </div>
    <div
      v-if="message.type === 'file'"
      style="border-radius: 4px; max-width: 70%"
    >
      <img
        :src="messageImageSrc"
        alt="File"
        style="width: 80px; max-height: 120px"
        @click="$previewImage([messageImageSrc])"
        v-if="isImage"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  props: {
    message: {
      type: Object,
      required: true,
    },
    avatarUrl: {
      type: String,
      default: '',
    },
  },
  computed: {
    ...mapGetters(['userInfo']),
    messageImageSrc() {
      return JSON.parse(this.message.content).fileUrl
    },
    isImage() {
      let fileUrl = JSON.parse(this.message.content).fileUrl
      return ['jpg', 'png', 'jpeg'].includes(fileUrl.split('.').pop())
    },
  },
  data() {
    return {}
  },
  methods: {
    getAvatar(sender) {
      // 根据 sender 返回不同的头像 URL
      return sender === 'a' ? '/path/to/avatar-a.png' : '/path/to/avatar-b.png'
    },
  },
}
</script>

<style scoped>
.message {
  display: flex;
  margin-bottom: 10px;
  gap: 12px;
}

.sent {
  flex-direction: row-reverse;
  .content {
    background-color: #66c2ff;
    color: #ffffff;
  }
}

.received {
  justify-content: flex-start;
}

.avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
}

.content {
  background-color: #ffffff;
  padding: 10px;
  border-radius: 4px;
  max-width: 70%;
  color: #66c2ff;
}

.text {
  margin: 0;
}

.timestamp {
  font-size: 12px;
  color: #888;
}
</style>
